<template>
    <div class="service-order-list-container">
        <!-- 搜索筛选区域 -->
        <div class="search-section">
            <el-card shadow="never" class="search-card">
                <div class="search-content">
                    <div class="search-left">
                        <el-form :model="searchForm" :inline="true" class="search-form">
                            <el-form-item label="名称:">
                                <el-input 
                                    v-model="searchForm.serviceName" 
                                    placeholder="输入服务名称" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="订单号:">
                                <el-input 
                                    v-model="searchForm.orderNo" 
                                    placeholder="输入订单号" 
                                    clearable
                                    style="width: 200px"
                                />
                            </el-form-item>
                            <el-form-item label="中英文:">
                                <el-select 
                                    v-model="searchForm.language" 
                                    placeholder="请选择" 
                                    clearable
                                    style="width: 150px"
                                >
                                    <el-option label="中文" value="zh" />
                                    <el-option label="英文" value="en" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="创建时间:">
                                <el-date-picker
                                    v-model="searchForm.startDate"
                                    type="date"
                                    placeholder="请选择日期"
                                    style="width: 150px"
                                />
                            </el-form-item>
                            <el-form-item label="创建时间:">
                                <el-date-picker
                                    v-model="searchForm.endDate"
                                    type="date"
                                    placeholder="请选择日期"
                                    style="width: 150px"
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                    <div class="search-right">
                        <el-button type="primary" @click="handleSearch">查询结果</el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-section">
            <el-card shadow="never" class="table-card">
                <el-table 
                    :data="tableData" 
                    v-loading="loading"
                    stripe
                    border
                    style="width: 100%"
                >
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="orderNo" label="订单号" />
                    <el-table-column prop="orgName" label="机构名称" />
                    <el-table-column prop="serviceName" label="服务名称" />
                    <el-table-column prop="orderStatus" label="订单状态" align="center">
                        <template #default="{ row }">
                            <el-tag 
                                :type="getStatusType(row.orderStatus)"
                                size="small"
                            >
                                {{ row.orderStatusName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="totalAmount" label="订单金额" align="right">
                        <template #default="{ row }">
                            ¥{{ row.totalAmount }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="expertName" label="专家名称" />
                    <el-table-column prop="orderTime" label="下单时间" width="180">
                        <template #default="{ row }">
                            {{ formatDateTime(row.orderTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" align="center" fixed="right">
                        <template #default="{ row }">
                            <el-button 
                                v-if="row.orderStatus === 1" 
                                type="warning" 
                                size="small" 
                                @click="handleCancelAppointment(row)"
                            >
                                取消预约
                            </el-button>
                            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-section">
            <el-card shadow="never" class="pagination-card">
                <div class="pagination-content">
                    <div class="pagination-info">
                        <span>总共{{ pagination.total }}条记录,当前在第{{ pagination.current }}页</span>
                    </div>
                    <el-pagination
                        v-model:current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :page-sizes="[10, 20, 50, 100]"
                        layout="prev, pager, next, jumper"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"
                    />
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getOrderPage } from '@/api/order/service-order';

// 定义数据类型
interface ServiceOrderItem {
    id: string;
    orderNo: string;
    orderAmount: number;
    merchantId: string;
    serviceId: string;
    serviceName: string;
    serviceCategory: string;
    orgId: string;
    orgName: string;
    expertId: string;
    expertName: string;
    expertAvatarUrl: string;
    expertExpertiseAreas: string;
    totalAmount: number;
    appointmentStartTime: string;
    appointmentEndTime: string;
    appointmentDuration: number;
    orderStatus: number;
    orderStatusName: string;
    paymentChannel: string;
    paymentChannelName: string;
    paymentStatus: number;
    paymentStatusName: string;
    orderTime: string;
    discountAmount: number;
    couponId: string;
    actualPaymentAmount: number;
    paymentTime: string;
    paymentTransactionId: string;
    remark: string;
    cancelReason: string;
    cancelTime: string;
    language: string;
    createTime: string;
    updateTime: string;
}

interface ServiceOrderPageParams {
    pageNum: number;
    pageSize: number;
    serviceName?: string;
    orderNo?: string;
    language?: string;
    startTime?: string;
    endTime?: string;
}

const router = useRouter();

// 搜索表单
const searchForm = reactive({
    serviceName: '',
    orderNo: '',
    language: '',
    startDate: '',
    endDate: ''
});

// 表格数据
const loading = ref(false);
const tableData = ref<ServiceOrderItem[]>([]);

// 分页数据
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
});

// 时间格式化函数
const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '-';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 获取状态类型
const getStatusType = (status: number) => {
    const statusMap: { [key: number]: string } = {
        0: 'warning',  // 待支付
        1: 'success',  // 已支付
        2: 'danger',   // 已取消
        3: 'success',  // 已完成
        4: 'info',     // 已退款
        5: 'warning'   // 支付中
    };
    return statusMap[status] || 'info';
};

// 获取服务订单列表
const fetchServiceOrderList = async () => {
    try {
        loading.value = true;
        const params: ServiceOrderPageParams = {
            pageNum: pagination.current,
            pageSize: pagination.size,
            serviceName: searchForm.serviceName || undefined,
            orderNo: searchForm.orderNo || undefined,
            language: searchForm.language || undefined,
            startTime: searchForm.startDate || undefined,
            endTime: searchForm.endDate || undefined
        };
        
        const res = await getOrderPage(params);
        
        const responseData = res as any;
        if (responseData && responseData.code === 200 && responseData.data) {
            tableData.value = responseData.data.records || responseData.data.list || [];
            pagination.total = responseData.data.total || responseData.data.pageTotal || 0;
        } else {
            const errorMsg = (responseData && (responseData.msg || responseData.message)) || '获取服务订单列表失败';
            ElMessage.error(errorMsg);
            tableData.value = [];
            pagination.total = 0;
        }
    } catch (error) {
        console.error('获取服务订单列表失败:', error);
        ElMessage.error('获取服务订单列表失败');
    } finally {
        loading.value = false;
    }
};

// 搜索方法
const handleSearch = () => {
    pagination.current = 1;
    fetchServiceOrderList();
};

// 分页方法
const handlePageChange = (page: number) => {
    pagination.current = page;
    fetchServiceOrderList();
};

const handleSizeChange = (size: number) => {
    pagination.size = size;
    pagination.current = 1;
    fetchServiceOrderList();
};

// 查看订单详情
const handleView = (row: ServiceOrderItem) => {
    router.push(`/service-order-detail/${row.id}`);
};

// 取消预约
const handleCancelAppointment = (row: ServiceOrderItem) => {
    ElMessageBox.confirm(
        `确定要取消订单 "${row.orderNo}" 的预约吗？`,
        '取消预约确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        ElMessage.success('预约已取消');
        // 这里可以调用取消预约API
    }).catch(() => {
        ElMessage.info('已取消操作');
    });
};

// 页面初始化
onMounted(() => {
    // 加载初始数据
    fetchServiceOrderList();
});
</script>

<style scoped>
.service-order-list-container {
    padding: 20px;
}

/* 搜索区域 */
.search-section {
    margin-bottom: 20px;
}

.search-card {
    border-radius: 8px;
}

.search-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin: 0;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.search-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 20px;
}

.table-card {
    border-radius: 8px;
}

/* 分页区域 */
.pagination-section {
    margin-bottom: 20px;
}

.pagination-card {
    border-radius: 8px;
}

.pagination-content {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    gap: 20px;
    align-items: center;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .service-order-list-container {
        padding: 10px;
    }
    
    .search-content {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }
    
    .search-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }
    
    .pagination-content {
        flex-direction: column;
        gap: 15px;
        align-items: center;
    }
}
</style>
